package com.whj.wkpt.service;

import com.whj.wkpt.dto.PageResultDTO;
import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.TaskApplication;
import com.whj.wkpt.mapper.TaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class TaskService {

    @Autowired
    private TaskMapper taskMapper;
    
    @Autowired
    private TaskApplicationService taskApplicationService;

    public Task createTask(Task task) {
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        task.setPublishDate(LocalDateTime.now());
        taskMapper.insert(task);
        return task;
    }

    public Task updateTask(Task task) {
        task.setUpdateTime(LocalDateTime.now());
        // 确保必须的字段不为空
        Task existingTask = findById(task.getTaskId());
        if (existingTask != null) {
            if (task.getEmployerId() == null) {
                task.setEmployerId(existingTask.getEmployerId());
            }
        }
        taskMapper.update(task);
        return task;
    }

    public Task findById(Long taskId) {
        return taskMapper.findById(taskId);
    }

    public List<Task> findAllTasks() {
        return taskMapper.findAll();
    }

    public List<Task> findByEmployerId(Long employerId) {
        return taskMapper.findByEmployerId(employerId);
    }

    public void deleteTask(Long taskId) {
        // 先删除与该任务关联的所有申请记录（解决外键约束问题）
        List<TaskApplication> taskApplications = taskApplicationService.findByTaskId(taskId);
        for (TaskApplication application : taskApplications) {
            taskApplicationService.deleteApplication(application.getApplicationId());
        }
        
        // 然后删除任务
        taskMapper.deleteById(taskId);
    }

    public List<Task> findByTitleContaining(String title) {
        return taskMapper.findByTitleContaining(title);
    }

    public List<Task> findByTaskStatus(String taskStatus) {
        return taskMapper.findByTaskStatus(taskStatus);
    }

    public List<Task> findByEmployerIdAndTitleContaining(Long employerId, String title) {
        return taskMapper.findByEmployerIdAndTitleContaining(employerId, title);
    }

    public List<Task> findByEmployerIdAndTaskStatus(Long employerId, String taskStatus) {
        return taskMapper.findByEmployerIdAndTaskStatus(employerId, taskStatus);
    }

    public List<Task> searchTasks(Long employerId, String title, String taskStatus) {
        if (title != null && !title.isEmpty() && taskStatus != null && !taskStatus.isEmpty()) {
            return taskMapper.findByEmployerIdAndTitleContainingAndTaskStatus(employerId, title, taskStatus);
        } else if (title != null && !title.isEmpty()) {
            return taskMapper.findByEmployerIdAndTitleContaining(employerId, title);
        } else if (taskStatus != null && !taskStatus.isEmpty()) {
            return taskMapper.findByEmployerIdAndTaskStatus(employerId, taskStatus);
        } else {
            return taskMapper.findByEmployerId(employerId);
        }
    }
    
    public List<Task> findByIds(List<Long> taskIds) {
        // 处理空列表情况，避免SQL语法错误
        if (taskIds == null || taskIds.isEmpty()) {
            return new ArrayList<>();
        }
        return taskMapper.findByIds(taskIds);
    }
    
    // 分页查询方法
    public PageResultDTO<Task> findTasksWithPagination(String title, String taskStatus, int page, int size) {
        int offset = page * size;
        List<Task> tasks;
        int totalElements;
        
        // 根据不同的查询条件选择不同的查询方法
        // 同时按标题和状态查询
        if (title != null && !title.isEmpty() && taskStatus != null && !taskStatus.isEmpty()) {
            tasks = taskMapper.findByTitleContainingAndTaskStatusWithPagination(title, taskStatus, offset, size);
            totalElements = taskMapper.countByTitleContainingAndTaskStatus(title, taskStatus);
        // 只按标题查询
        } else if (title != null && !title.isEmpty()) {
            tasks = taskMapper.findByTitleContainingWithPagination(title, offset, size);
            totalElements = taskMapper.countByTitleContaining(title);
        // 只按状态查询
        } else if (taskStatus != null && !taskStatus.isEmpty()) {
            tasks = taskMapper.findByTaskStatusWithPagination(taskStatus, offset, size);
            totalElements = taskMapper.countByTaskStatus(taskStatus);
        // 无条件查询所有任务
        } else {
            tasks = taskMapper.findAllWithPagination(offset, size);
            totalElements = taskMapper.countAll();
        }
        
        return new PageResultDTO<>(tasks, page, size, totalElements);
    }
}